<template>
  <div class="index-container">
    <el-drawer v-model="dialogFormVisible" size="30%" @close="close">
      <template #header>
        <h4>{{ title }}约见信息</h4>
      </template>

      <template #default>
        <div class="content">
          <el-form
            ref="formRef"
            label-width="100px"
            :model="form"
            :rules="rules"
          >
            <el-form-item label="男方信息" prop="mid">
              <el-select
                v-model="form.mid"
                filterable
                remote
                :remote-method="handleSearchByMan"
                :loading="loading1"
                placeholder="请选择男方信息"
                @change="handleSelectByMan"
              >
                <el-option
                  v-for="item in manOptions"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
                <el-option v-if="isEmpty1" disabled value="">
                  无匹配数据
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="女方信息" prop="otherid">
              <el-select
                v-model="form.otherid"
                filterable
                remote
                :remote-method="handleSearchByWoman"
                :loading="loading2"
                placeholder="请选择女方信息"
                @change="handleSelectByWoman"
              >
                <el-option
                  v-for="item in womanOptions"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                />
                <el-option v-if="isEmpty2" disabled value="">
                  无匹配数据
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="约见地点" prop="meet_addr">
              <el-input
                v-model.trim="form.meet_addr"
                placeholder="请填写约见地点"
              />
            </el-form-item>
            <el-form-item label="约见时间" prop="meet_at">
              <el-date-picker
                v-model="form.meet_at"
                placeholder="请选择约见时间"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm"
                format="YYYY-MM-DD HH:mm"
                date-format="YYYY-MM-DD"
                time-format="HH:mm"
                style="width: 100%"
              />
            </el-form-item>
            <el-form-item label="服务红娘" prop="maker_id">
              <el-select
                v-model="form.maker_id"
                filterable
                remote
                :remote-method="handleSearch"
                :loading="loading3"
                placeholder="请选择服务红娘"
                @change="handleSelect"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.realname"
                  :value="item.id"
                />
                <el-option v-if="isEmpty3" disabled value="">
                  无匹配数据
                </el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="pay-button-group">
          <el-button type="primary" @click="submitForm('formRef')">
            保存
          </el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>
<script>
  import { defineComponent } from 'vue'
  import { getMemberList } from '@/api/member'
  import { getUserList } from '@/api/user'
  import { doAdd } from '@/api/meet'
  import { debounce } from 'lodash-es'

  export default defineComponent({
    name: 'MeetDrawer',
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')
      const state = reactive({
        formRef: null,
        baseForm: {},
        form: {
          mid: '',
          otherid: '',
          meet_addr: '',
          meet_at: '',
          maker_id: '',
        },
        options: [],
        manOptions: [],
        womanOptions: [],
        loading1: false,
        isEmpty1: false,
        loading2: false,
        isEmpty2: false,
        loading3: false,
        isEmpty3: false,
        title: '',
        dialogFormVisible: false,
        rules: {
          mid: [{ required: true, trigger: 'change', message: '请选择男方' }],
          otherid: [
            { required: true, trigger: 'change', message: '请选择女方' },
          ],
          meet_addr: [
            { required: true, trigger: 'change', message: '请填写约见地点' },
          ],
          meet_at: [
            { required: true, trigger: 'change', message: '请填写约见时间' },
          ],
          maker_id: [
            { required: true, trigger: 'change', message: '请选择服务红娘' },
          ],
        },
      })
      const showEdit = (row) => {
        if (!row) {
          state.title = '添加'
        } else {
          state.title = '编辑'
          state.form = JSON.parse(JSON.stringify(row))

          state.options = [
            {
              id: state.form.maker_id,
              realname: state.form.realname,
            },
          ]
          state.manOptions = [
            {
              id: row.mid,
              username: state.form.base.username,
            },
          ]
          state.womanOptions = [
            {
              id: row.otherid,
              username: state.form.obase.username,
            },
          ]
          console.log(state.form)
          console.log(state.womanOptions)
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {}
        state.dialogFormVisible = false
      }
      const submitForm = (formName) => {
        state[formName].validate(async (valid) => {
          state.baseForm = {
            id: state.form.id,
            mid: state.form.mid,
            otherid: state.form.otherid,
            meet_at: state.form.meet_at,
            meet_addr: state.form.meet_addr,
            maker_id: state.form.maker_id,
          }
          if (valid) {
            const { msg } = await doAdd(state.baseForm)
            $baseMessage(msg, 'success', 'vab-hey-message-success')
            emit('fetch-data')
            close()
          }
        })
      }

      // 防抖处理（300ms）
      const debouncedSearchForMan = debounce(async (query) => {
        if (!query) {
          state.manOptions = []
          return
        }

        try {
          state.loading1 = true
          state.isEmpty1 = false

          // 替换为你的实际 API 调用
          const data = await getMemberList({
            keywords: query,
            gender: 1,
          })
          state.manOptions = data.data
          state.isEmpty1 = !data.data?.length
        } catch (error) {
          $baseMessage('搜索失败', 'error', 'vab-hey-message-error')
        } finally {
          state.loading1 = false
        }
      }, 300)
      const handleSearchByMan = (query) => {
        debouncedSearchForMan(query)
      }
      const handleSelectByMan = (value) => {
        console.log('选中值:', value)
        // 这里处理选中后的逻辑
      }
      // 防抖处理（300ms）
      const debouncedSearchForWoman = debounce(async (query) => {
        if (!query) {
          state.womanOptions = []
          return
        }

        try {
          state.loading2 = true
          state.isEmpty2 = false

          // 替换为你的实际 API 调用
          const data = await getMemberList({
            keywords: query,
            gender: 2,
          })
          state.womanOptions = data.data
          state.isEmpty2 = !data.data?.length
        } catch (error) {
          $baseMessage('搜索失败', 'error', 'vab-hey-message-error')
        } finally {
          state.loading2 = false
        }
      }, 300)
      const handleSearchByWoman = (query) => {
        debouncedSearchForWoman(query)
      }
      const handleSelectByWoman = (value) => {
        console.log('选中值:', value)
        // 这里处理选中后的逻辑
      }

      // 防抖处理（300ms）
      const debouncedSearch = debounce(async (query) => {
        if (!query) {
          state.options = []
          return
        }

        try {
          state.loading3 = true
          state.isEmpty3 = false

          // 替换为你的实际 API 调用
          const data = await getUserList({
            keywords: query,
          })
          state.options = data.data
          state.isEmpty3 = !data.data?.length
        } catch (error) {
          $baseMessage('搜索失败', 'error', 'vab-hey-message-error')
        } finally {
          state.loading3 = false
        }
      }, 300)
      const handleSearch = (query) => {
        debouncedSearch(query)
      }
      const handleSelect = (value) => {
        console.log('选中值:', value)
        // 这里处理选中后的逻辑
      }

      // 组件卸载时取消防抖
      onUnmounted(() => {
        debouncedSearch.cancel()
        debouncedSearchForMan.cancel()
        debouncedSearchForWoman.cancel()
      })
      return {
        ...toRefs(state),
        showEdit,
        close,
        handleSearchByMan,
        handleSelectByMan,
        handleSearchByWoman,
        handleSelectByWoman,
        handleSearch,
        handleSelect,
        submitForm,
      }
    },
  })
</script>
<style lang="scss">
  .index-container {
    .el-drawer__header {
      height: 50px;
      padding: 0px 20px;
      margin-bottom: 0px;
      color: #000000;
      background-color: rgb(245, 245, 245);
    }

    .el-drawer__footer {
      text-align: center;
    }

    .content {
      .el-form-item__label {
        display: flex;
        justify-content: center;
        align-items: center;
        height: auto; /* 或者你需要的高度 */
      }
      .el-form-item__content {
        line-height: 25px;
      }
    }
  }
</style>
